package cn.edu.swu.xyx.book;

import cn.edu.swu.xyx.repo.DatabaseService;
import cn.edu.swu.xyx.repo.ResultSetVisitor;
import cn.edu.swu.xyx.utils.HtmlHelper;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/admin/books")
public class BookServlet extends HttpServlet {

    public final static int DEFAULT_PAGE_SIZE = 5;
    public final static int DEFAULT_PAGE = 1;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        int page = DEFAULT_PAGE;
        int size = DEFAULT_PAGE_SIZE;

        String inputPage = request.getParameter("page");
        String inputSize = request.getParameter("size");
        if (inputPage != null) {
            page = Integer.parseInt(inputPage);
        }
        if (inputSize != null) {
            size = Integer.parseInt(inputSize);
        }

        ServletContext context = request.getServletContext();
        DatabaseService service = (DatabaseService)context.getAttribute(DatabaseService.CONTEXT_KEY);
        try {
            String sql = String.format(
                    "SELECT * FROM book ORDER BY id DESC LIMIT %s OFFSET %s",
                    size, (page - 1) * size);

            List<Book> books = service.query(sql, new BookResultSetVisitor());
            int pages = this.getPages(service, size);
            String pager = HtmlHelper.buildPager("./books", pages, page, size);

            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                String table = HtmlHelper.buildBooksTable(books);
                String html = HtmlHelper.wrapHtml(table + "<br><br>" + pager);
                writer.write(html);
                writer.flush();
            }
        } catch (IOException | SQLException e) {
            throw new ServletException(e);
        }
    }

    private int getPages(DatabaseService service, int pageSize) throws SQLException {
        String sql = String.format("SELECT CEIL(COUNT(*) / %s) AS pages FROM book", pageSize);
        List<Integer> pages = service.query(sql, new ResultSetVisitor<Integer>() {
            @Override
            public List<Integer> visit(ResultSet rs) throws SQLException {
                rs.next();
                return List.of(rs.getInt("pages"));
            }
        });
        return pages.get(0);
    }


}
